package com.api.shuigui.service.impl;

import cn.hutool.core.convert.Convert;
import com.api.shuigui.pojo.DocContent;
import com.api.shuigui.pojo.PageBean;
import com.api.shuigui.service.DocContentService;
import com.api.shuigui.utils.DocUtil;
import com.wbi.util.Util;
import com.weaver.ecology.search.model.ImageFile;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.MD5;
import weaver.hrm.User;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

public class DocContentServiceImpl implements DocContentService {

    BaseBean bb = new BaseBean();

    private static final Logger LOGGER = LoggerFactory.getLogger("DocContentServiceImpl");

    @Override
    public Map<String, Object> getDocContent(Map<String, Object> params) throws IOException {
        //处理结果
        Map<String, Object> result = new HashMap<>();
        //获取的当前的页码
        int pageNum = Integer.parseInt(params.get("pageNum").toString());
        //获取每页显示的条数
        int pageSize = Integer.parseInt(params.get("pageSize").toString());
        //获取目录
        String category = Util.null2String(params.get("category"));
        //获取搜索框输入的数据
        String search = Util.null2String(params.get("search"));

        Object selectYearsObj = params.get("selectYears");
        String selectYears = Convert.toStr(selectYearsObj,"");


        if (pageNum <= 0) {
            pageNum = 1;
        }
        PageBean<DocContent> pb = new PageBean<>();
        //封装参数
        pb.setCurrentPage(pageNum);
        pb.setRows(pageSize);

        //查询总条数
        int totalSize = findTotal(category, search,selectYears);

        pb.setTotalCount(totalSize);
        //查询数据
        int start = (pageNum - 1) * pageSize;
        List<DocContent> list = getAllDoc(start, pageSize, category, search,selectYears);
        pb.setList(list);
        result.put("data", pb);
        bb.writeLog("结果是1-----------" + result);
        return result;
    }

    /**
     * 通过ID获取数据库中的内容
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> getDocHtml(Integer id) throws IOException {
        Map<String, Object> result = new HashMap<>();
        bb.writeLog("getDocHtml------------------------");
        RecordSet re = new RecordSet();
        String redbType = re.getDBType();
        boolean mysql = redbType.equals("mysql");
        boolean sqlserver = redbType.equals("sqlserver");
        boolean pgsql = redbType.equals("postgresql");
        //doccreaterid  创建人
        //doccreatedate 创建日期
        //doclastmoddate 文档最后修改时间

        String sql="";
        if (sqlserver) {
            sql = "select doccreaterid,docsubject,doccreatedate,doclastmoddate,doccontent from docDetail where id = ?";
        }else{
            sql = "select a.doccreaterid,a.docsubject,a.doccreatedate,a.doclastmoddate,a.doclastmoduserid,b.doccontent from docDetail a inner join docdetailcontent b on b.docid = a.id where id = ?";
        }
        boolean b = re.executeQuery(sql, id);
        String content = "";
        String docSubject = "";
        String docCreater="";
        String doccreatedate = "";
        String doclastmoddate = "";
        String docLastUser = "";
        if (b && re.next()) {

             int doccreaterid = Integer.parseInt(Util.null2String(re.getString("doccreaterid")));
            User user=new User(doccreaterid);
            docCreater=user.getUsername();
            doccreatedate = Util.null2String(re.getString("doccreatedate"));
            doclastmoddate = Util.null2String(re.getString("doclastmoddate"));
            content = Util.null2String(re.getString("doccontent"));
            docSubject = Util.null2String(re.getString("docsubject"));

            int doclastmoduserid = Integer.parseInt(Util.null2String(re.getString("doclastmoduserid")));
            User lastUser = new User(doclastmoduserid);
            docLastUser = lastUser.getUsername();
        }
        List<ImageFile> imglist = new ArrayList<>();
        /*if(!"".equals(content)){*/
        //如果获取的内容不为空，则获取该文档对应的图片
        String msql = "select i.imagefilename,i.imagefileid,i.filerealpath from DocImageFile d left join ImageFile i on i.imagefileid = d.imagefileid where d.docid = ?";
        RecordSet re1 = new RecordSet();
        boolean b1 = re1.executeQuery(msql, id);
        List<Map<String, Object>> list = new ArrayList<>();
        while (b1 && re1.next()) {
            ImageFile imageFile = new ImageFile();
            String filename = Util.null2String(re1.getString("imagefilename"));
            String filepath = Util.null2String(re1.getString("filerealpath"));
            String fileid = Util.null2String(re1.getString("imagefileid"));
            //封装图片的名称
            imageFile.setImagefilename(filename);
            //封装图片的路径
            imageFile.setFilerealpath(filepath);
            String filetype = Util.null2String(filename.substring(filename.lastIndexOf(".") + 1));
            if (filetype.equals("png") || filetype.equals("jpg") || filetype.equals("jpeg") || filetype.equals("gif")||filetype.equals("PNG") || filetype.equals("JPG") || filetype.equals("JPEG") || filetype.equals("GIF")) {
                imageFile.setImagefiletype(filetype);
                imglist.add(imageFile);
            } else {
                Map<String, Object> file = new HashMap<>();
                file.put("fileid", fileid);
                file.put("type", filetype);
                file.put("filename", filename);
                list.add(file);
            }
        }
        result.put("file", list);
        //提取html文件body中的内容
        content = DocUtil.ReplaceHtmlBody(content);
        //处理图片，移动到对应文件夹
        for (ImageFile imageFile : imglist) {
            //文件存储路径
            String savePath = "interface/imgs/doc/" + id + "/";
            //图片名称
            String name = imageFile.getImagefilename();
            String type = imageFile.getImagefiletype();
            //实际文件名
            String realName = id + "_" + new MD5().getMD5ofStr(name) + "." + type;
            //图片路径
            String imgPath = imageFile.getFilerealpath();
            //图片最终地址
            String imgUrl;
            //判断路径下是否存在该文件
            if (DocUtil.isCategoryByName(realName, savePath)) {
                imgUrl = "/" + savePath + realName;
            } else {
                imgUrl = DocUtil.readZipFile(imgPath, name, realName, savePath);
                //替换html img标签中的内容
            }
            content = DocUtil.replaceHtmlTag(content, imgUrl);
        }
        result.put("docCreater", docCreater);
        result.put("doccreatedate", doccreatedate);
        result.put("doclastmoddate", doclastmoddate);
        result.put("content", content);
        result.put("title", docSubject);
        result.put("docLastUser", docLastUser);
        //返回处理好的最终结果
        return result;
    }
    /**
     * 获取人才团队 
     */
    @Override
    public Map<String, Object> getRoleTeam(Map<String, Object> params) {
        LOGGER.info("getRoleTeam -----------");
        Map<String, Object> result = new HashMap<>();
        ArrayList list=new ArrayList();
        RecordSet rs = new RecordSet();
        String sql = "select wd,wdmc,px,lx from uf_rctd order by px asc";

        boolean execute = rs.execute(sql);
        LOGGER.info("sql = {}",sql);
        if(execute){
            while (rs.next()){
                HashMap<String,Object > map=new HashMap();
                map.put("wd",Util.null2String(rs.getString("wd")));
                map.put("wdmc",Util.null2String(rs.getString("wdmc")));
                map.put("px",Util.null2String(rs.getString("px")));
                // 默认 0 把
                Integer lx = Convert.toInt(rs.getString("lx"), 0);
                map.put("lx",lx);
                list.add(map);
            }
        }
        LOGGER.info("list = {}",list);
        result.put("data", list);
        return result;
    }

    public List<DocContent> getAllDoc(int pageNum, int pageSize, String category, String search, String selectYears) throws IOException {
        //初始化数据库连接
//        RecordSet re = new RecordSet();
        //得到数据库类型
        String dbType = "Mysql"; // re.getDBType();
        //初始化sql语句
        StringBuilder stringBuffer = new StringBuilder();
        //获取当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String currentDate = sdf.format(new Date());
        String sql = "";
        if (dbType.equals("sqlserver")) {
            //Sql Server
            sql = "select top " + pageSize + " * from (select a.id,a.docsubject,a.doccontent,a.doccreatedate,a.sffb,a.doccreatetime,ROW_NUMBER() " +
                    " over (ORDER BY a.doccreatedate desc,a.doccreatetime desc) as rowNumber from DocDetail a inner join DocSecCategory b on a.seccategory= b.id " +
                    "where  b.id in (" + category + ") and a.doctype = 1 and a.docstatus in(1,2)";
        } else {
            //Mysql
            sql = "select a.id,c.doccontent,a.docsubject,a.doccreatedate,a.sffb,a.doccreatetime from DocDetail a inner join DocSecCategory b on a.seccategory= b.id inner join " +
                    " docdetailcontent c on c.docid = a.id" +
                    " where  b.id in (" + category + ") and a.doctype = 1 and a.docstatus in(1,2)";
        }
        LOGGER.info("sql = {} ",sql);
        LOGGER.info("dbType = {} ",dbType);
        stringBuffer.append(sql);
        //如果有搜索条件
        if (!"".equals(search)) {
            if (dbType.equals("sqlserver")) {
                //Sql Server
                stringBuffer.append(" and (a.docsubject like '%").append(search).append("%' or a.doccontent like '%").append(search).append("%')");
            } else {
                //Mysql
                stringBuffer.append(" and (a.docsubject like '%").append(search).append("%' or c.doccontent like '%").append(search).append("%')");
            }
        }
        if (!selectYears.isEmpty()){
            String where = " and LEFT(a.doccreatedate, 4) = '"+selectYears+"'";
            stringBuffer.append(where);
        }
        if (dbType.equals("sqlserver")) {
            //Sql Servel
            stringBuffer.append(" )c where rowNumber > ").append(pageNum).append(" ORDER BY a.istop desc, c.doccreatedate desc,c.doccreatetime desc");
        } else {
            //Mysql
            stringBuffer.append("ORDER BY a.istop desc, a.doccreatedate desc,a.doccreatetime desc limit ").append(pageNum).append(",").append(pageSize);
        }
        RecordSet re = new RecordSet();
        boolean b = re.execute(stringBuffer.toString());
        List<DocContent> list = new ArrayList<>();
        while (b && re.next()) {
            DocContent doc = new DocContent();
            //解析doccontent中的字符
            String content = Util.null2String(re.getString("doccontent"));
            String result = "";
            if (!"".equals(content)) {
                result = getDocContent(content, "span");
                if ("".equals(result)) {
                    //如果span标签内容为空，则取p标签
                    result = getDocContent(content, "p");
                }
            }
            doc.setDocContent(result);
            doc.setDocSubject(Util.null2String(re.getString("docsubject")));
            doc.setDocCreateDate(Util.null2String(re.getString("doccreatedate")));
            // 如果为空的话 就是 1 1表示隐藏
            doc.setSffb(Convert.toInt(re.getString("sffb"), 1));
            LOGGER.info("doc = {} ",doc);
            Integer id = re.getInt("id");
            doc.setId(id);
            String imgUrl = "";
            //如果文档中有信息，则查找是否有图片
            //通过id查询文档对应的图片路径和名称
            String msql;
            if (dbType.equals("sqlserver")) {
                //Sql Server
                msql = "select top 1 i.imagefilename,i.filerealpath from DocImageFile d left join ImageFile i on i.imagefileid = d.imagefileid where d.docid = ?";
            } else {
                //Mysql
                msql = "select i.imagefilename,i.filerealpath from DocImageFile d left join ImageFile i on i.imagefileid = d.imagefileid where d.docid = ? limit 1";
            }
            RecordSet re1 = new RecordSet();
            boolean b1 = re1.executeQuery(msql, id);
            //获得ecology路径
            //有文件
            if (b1 && re1.next()) {
                String filename = re1.getString("imagefilename");
                String filepath = re1.getString("filerealpath");
                //判断是否是文档类附件
                String filetype = Util.null2String(filename.substring(filename.lastIndexOf(".") + 1));
                //得到最终存储的图片名称
                String realName = id + "_" + new MD5().getMD5ofStr(filename) + "." + filetype;
                if (filetype.equals("png") || filetype.equals("jpg") || filetype.equals("jpeg") ||
                        filetype.equals("gif")
                ) {
                    //是图片
                    String savePath = "interface/imgs/doc/" + id + "/";
                    //判断路径下是否存在该文件
                    if (DocUtil.isCategoryByName(realName, savePath)) {
                        //存在
                        imgUrl = "/" + savePath + realName;
                    } else {
                        //不存在则解压文件获取图片
                        imgUrl = DocUtil.readZipFile(filepath, filename, realName, savePath);
                    }
                }
            } else if (!"".equals(DocUtil.ContentIsImgurl(content))) {
                //查看是否存在带链接的图片
                imgUrl = DocUtil.ContentIsImgurl(content);
            }
            doc.setImgUrl(imgUrl);
            list.add(doc);
        }
        bb.writeLog("结果是-----------" + list);
        return list;
    }

    public int findTotal(String category, String search, String selectYears) {
        RecordSet re = new RecordSet();
        String dbType = re.getDBType();
        String sql = this.genGetTotalSql(dbType, search, category, selectYears);
        bb.writeLog("统计sql是----" + sql);
        boolean b = re.executeQuery(sql);
        int total = 0;
        if (b && re.next()) {
            total = re.getInt(1);
        }
        return total;
    }

    public String genGetTotalSql(String dbType,String search,String category,String selectYears) {
        String sql = "";
        StringBuilder stringBuffer = new StringBuilder();
        if (dbType.equals("sqlserver")) {
            //Sql Server
            sql = "select count(1) from DocDetail a left join DocSecCategory b on a.seccategory = b.id where b.id in("+category+") ";
        } else {
            //Mysql
            sql = "select count(1) from DocDetail a inner join DocSecCategory b on a.seccategory = b.id inner join docdetailcontent c on c.docid = a.id where b.id in("+category+")  and a.doctype = 1 ";
        }
        stringBuffer.append(sql);
        //如果有搜索条件
        if (!"".equals(search)) {
            if (dbType.equals("sqlserver")) {
                //Sql Server
                stringBuffer.append(" and (a.docsubject like '%").append(search).append("%' or a.doccontent like '%").append(search).append("%')");
            } else {
                //Mysql
                stringBuffer.append(" and (a.docsubject like '%").append(search).append("%' or c.doccontent like '%").append(search).append("%')");
            }

        }
        if (!selectYears.isEmpty()){
            String where = " and LEFT(a.doccreatedate, 4) = '"+selectYears+"'";
            stringBuffer.append(where);
        }
        return stringBuffer.toString();
    }

    /**
     * 提取html中指定标签的值 span or p
     *
     * @param content
     * @param tag
     * @return
     */
    private String getDocContent(String content, String tag) {
        try {
            //将string文本转换成html文本
            Document doc = Jsoup.parse(content);
            //得到全部p标签
            List<Element> links = doc.getElementsByTag(tag);
            //实例化stringbuffer
            StringBuilder buffer = new StringBuilder();
            for (Element link : links) {
                //将文本提取出来
                buffer.append(link.text().trim());
            }
            return buffer.toString().trim();
        } catch (Exception e) {
            bb.writeLog(e.getMessage());
            return content;
        }
    }

}

